package com.palm.hubo2o.ui;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.preference.Preference;
import android.support.v7.preference.PreferenceDialogFragmentCompat;
import android.support.v7.preference.PreferenceFragmentCompat;

import com.palm.hubo2o.BaseActivity;
import com.palm.hubo2o.R;
import com.palm.hubo2o.network.PalmSession;
import com.palm.hubo2o.view.AlertDialogPreference;

/**
 * Created by wongqi on 16/6/22.
 */
public class SettingsActivity extends BaseActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);
        getSupportFragmentManager().beginTransaction().add(R.id.root_settings, new SettingFragment()).commit();

    }

    public static class SettingFragment extends PreferenceFragmentCompat {

        @Override
        public void onCreatePreferences(Bundle bundle, String s) {
            addPreferencesFromResource(R.xml.settings);
            Preference cancel = findPreference(getString(R.string.pref_key_exit));
            cancel.setVisible(PalmSession.isLogin());
        }

        @Override
        public void onDisplayPreferenceDialog(Preference preference) {
            if (preference instanceof AlertDialogPreference) {
                String key = preference.getKey();
                if (key == null)
                    return;
                DialogFragment f = ExitPreferenceDialogFragmentCompat.newInstance(preference.getKey());
                f.setTargetFragment(this, 0);
                f.show(this.getFragmentManager(), "android.support.v7.preference.PreferenceFragment.DIALOG");
            } else {
                super.onDisplayPreferenceDialog(preference);
            }
        }
    }

    public static class ExitPreferenceDialogFragmentCompat extends PreferenceDialogFragmentCompat {

        public static ExitPreferenceDialogFragmentCompat newInstance(String key) {
            ExitPreferenceDialogFragmentCompat fragment = new ExitPreferenceDialogFragmentCompat();
            Bundle b = new Bundle(1);
            b.putString("key", key);
            fragment.setArguments(b);
            return fragment;
        }

        public ExitPreferenceDialogFragmentCompat() {
        }

        @Override
        public void onDialogClosed(boolean positive) {
            if (positive) {
                PalmSession.logout();
                getActivity().finish();
            }
        }
    }
}
